<template>
	<view class="editPresc-wrap" @click="hideSearchPanel">
		<view class="editPresc-box">
			<u-title value="请选择疾病名称"></u-title>
			<view class="sickness">
				<view class="sickness-item-wrapper" v-for="(item, index) in sicknessSelectedTemp" :key="index" @click="delSickness(item, index)">
					<view class="sickness-item">{{ item.sicknessName }}</view>
					<image
						src="https://cdn.yingpaipay.com/%E5%88%87%E5%9B%BE%2017%402x.png"
						mode="widthFix"
						class="del-icon"
					/>
				</view>
				<view class="add" @click.stop="showSearchPanel">+添加诊断</view>
			</view>
			<view class="search-panel-mask" style="">
				<view class="search-panel" v-if="searchPanelVisible" @click.stop="showSearchPanel">
					<view class="search-bar" :style="{ borderBottom: sicknessList.length ? '2rpx solid #E8E8E8' : 'none' }">
						<view class="input">
							<image
								src="https://cdn.yingpaipay.com/%E5%88%87%E5%9B%BE%2021%402x.png"
								mode="widthFix"
							/>
							<input type="text"
								@input="getSicknessList"
								v-model="sicknessKeyword"
								class="sickness-name"
								placeholder-class="input-place"
								placeholder="请输入疾病名称"
							/>
						</view>
						<view @click.stop="hideSearchPanel">
							<image
								v-show="sicknessKeyword"
								src="https://cdn.yingpaipay.com/%E5%88%87%E5%9B%BE%2017%402x.png"
								mode="widthFix"
								class="del-icon"
							/>
						</view>
					</view>
					<scroll-view scroll-y class="sickness-name-list" v-show="sicknessKeyword && sicknessList[0].sicknessName">
						<view class="sickness-name-item" v-for="(sickness, index) in sicknessList" :key="index" @click="sicknessClick(sickness)">
							<text>{{ sickness.code }}</text>-<text>{{ sickness.sicknessName }}</text>
						</view>
					</scroll-view>
				</view>
			</view>

			<view style="margin-top: 20rpx;"></view>
			<u-title value="请选择症状"></u-title>
			<view class="sympotm-wrapper">
				<picker style="width: 100%;" mode="selector" :range="sympotmList" range-key="name" @change="sympotmNameChange"
					:value="sympotmList">
					<view class="sympotm">
						<view class="item-right-value" v-for="(item, index) in sympotmSelectedTemp" :key="index">
							<text>{{ item.name }}</text>
							<view @click="delSympotm(item, index)">
								<image
									src="https://cdn.yingpaipay.com/%E5%88%87%E5%9B%BE%2017%402x.png"
									mode="widthFix"
									class="del-icon"
								/>
							</view>
						</view>
						<view class="add">+添加症状</view>
					</view>
				</picker>
			</view>

			<view style="margin-top: 20rpx;"></view>
			<u-title value="Rp"></u-title>
			<view class="pharmacyList">
				<view class="paharmacy_name_txt">药房</view>
				<picker :range="pharmacyList" range-key="name" @change="pharmacyChange" :value="pharmacy_index">
					<view class="item-right">
						<view v-if="!pharmacy_id_raw && pharmacy_index == -1" class="item-right-select">请选择药房</view>
						<view v-if="pharmacy_id_raw && pharmacy_index == -1" class="item-right-value">{{ pharmacy_obj.name }}</view>
						<view v-if="pharmacy_index != -1" class="item-right-value">{{ pharmacyList[pharmacy_index].name }}</view>
						<image class="item-right-next" src="http://k8s.vendingtech.vip/images/next_icon@2x.png"></image>
					</view>
				</picker>
			</view>
			<view class="editPresc-drug-list">
				<u-show-goods v-if="recipeForm.recipeDetailDTO.length > 0"
					v-for="(item, index) in recipeForm.recipeDetailDTO" :key="index" :data="item"
					:type="recipeForm.recipeType == 0 ? '2' : '0'" @onClickOne="deleteDosage(index)"
					@onClickTwo="gotoRouter('/pages-doctor/wmDosage/wmDosage?goodsId=' + item.id)"></u-show-goods>
			</view>
			<view class="editPresc-drug-btn" @click="check_druglist">设置药品</view>
		</view>

		<!-- 中药 -->
		<view class="editPresc-form" v-if="recipeForm.recipeType == 1">
			<uni-forms label-width="100" :rules="rules" :value="recipeForm.drugUseVo" ref="form" err-show-type="toast">
				<uni-forms-item label="用药数量" name="commodityNum">
					<uni-easyinput @input="checkDisabledBtn" :maxlength="20" type="number"
						v-model.number="recipeForm.drugUseVo.commodityNum" placeholder="请输入用药数量" />
				</uni-forms-item>

				<uni-forms-item label="用药频率" name="frequency">
					<picker mode="selector" :range="frequencyList" @change="frequencyChange"
						:value="recipeForm.drugUseVo.frequency">
						<view class="item-right">
							<view v-if="!recipeForm.drugUseVo.frequency" class="item-right-select">请选择用药频率</view>
							<image v-if="!recipeForm.drugUseVo.frequency" class="item-right-next"
								src="http://k8s.vendingtech.vip/images/next_icon@2x.png"></image>
							<view v-if="recipeForm.drugUseVo.frequency" class="item-right-value">{{ recipeForm.drugUseVo.frequency }}</view>
						</view>
					</picker>
				</uni-forms-item>

				<uni-forms-item label="单次用量" name="onceDosage">
					<div class="flex-row-end">
						<uni-easyinput @input="checkDisabledBtn" type="text" v-model="recipeForm.drugUseVo.onceDosage"
							placeholder="请输入单次用量" />
						<view style="padding-left: 16rpx;line-height: 36px;">克/次</view>
					</div>
				</uni-forms-item>

				<uni-forms-item label="用药方法" name="useMethod">
					<picker mode="selector" :range="useMethodList" @change="useMethodChange"
						:value="recipeForm.drugUseVo.useMethod">
						<view class="item-right">
							<view v-if="!recipeForm.drugUseVo.useMethod" class="item-right-select">请选择用药方法</view>
							<image v-if="!recipeForm.drugUseVo.useMethod" class="item-right-next"
								src="http://k8s.vendingtech.vip/images/next_icon@2x.png"></image>
							<view v-if="recipeForm.drugUseVo.useMethod" class="item-right-value">{{ recipeForm.drugUseVo.useMethod }}</view>
						</view>
					</picker>
				</uni-forms-item>
				
				<uni-forms-item label="药量天数" name="totalCharge">
					<view class="flex-row-end">
						<uni-easyinput @input="checkDisabledBtn" type="text" v-model="recipeForm.drugUseVo.totalCharge" placeholder="请输入用药的天数" />
						<view style="padding-left: 16rpx;line-height: 36px;">天</view>
					</view>
				</uni-forms-item>

				<uni-forms-item label="医嘱" name="remark" :borderBottom="false"></uni-forms-item>

				<textarea @input="checkDisabledBtn" placeholder-class="textarea-place" :maxlength="1000"
					class="editPresc-form-text" v-model="recipeForm.drugUseVo.remark" placeholder="请填写医嘱" />
			</uni-forms>
		</view>

		<u-bottom-button v-if="!id" value="保存常用处方" :disabled="disabled" @click="formSubmit(0)"></u-bottom-button>
		<u-bottom-button v-if="id" type="2" value1="删除常用处方" value2="修改常用处方" @clickOne="removeDrRecipe" @clickTwo="formSubmit(1)"></u-bottom-button>
	</view>
</template>

<script>
import uTitle from '@/components/u-title/u-title.vue';
import uBottomButton from '@/components/u-bottom-button/u-bottom-button.vue';
import uShowGoods from '@/components/u-show-goods/u-show-goods.vue';
import uniEasyinput from '@/components/uni/uni-easyinput/uni-easyinput.vue';
import uniForms from '@/components/uni/uni-forms/uni-forms.vue';
import uniFormsItem from '@/components/uni/uni-forms-item/uni-forms-item.vue';
import uniDataSelect from '../components/uni-data-select/uni-data-select.vue';
import { mapState, mapMutations } from 'vuex';
import { onlyResolvesLast } from '@/utils/util.js';
export default {
	components: {
		uBottomButton,
		uTitle,
		uShowGoods,
		uniForms,
		uniFormsItem,
		uniEasyinput,
		uniDataSelect
	},
	computed: {
		...mapState({
			recipeForm: state => state.recipeForm
		}),
		prescType() {
			return this.recipeForm.recipeType == 1 ? 'GB-21' : 'ICD-10_6'
		}
	},
	data() {
		return {
			id: null,
			disabled: true,
			category: '4,5,6', // 药品分类  4,5,6西药 7中药
			frequencyList: [], // 用药频率列表
			useMethodList: [], // 用药方法列表
			
			pharmacy_index: -1, // 选中药房下标
			pharmacyList: [], // 药房列表
			pharmacy_obj: { name: '好药房', id: 111 },   // 修改时的药房数据
			pharmacy_id_raw: false,  // 是否用第一次修改接口拿的数据
			
			sicknessKeyword: '',
			sicknessSelectedTemp: [],
			sicknessList: [],
			searchPanelVisible: false,
			
			sympotmSelectedTemp: [],
			sympotmList: [
				{value: "1", name: "低热"},
				{value: "2", name: "高热"},
				{value: "3", name: "孕妇"},
				{value: "4", name: "高血压"},
				{value: "5", name: "糖尿病"},
				{value: "6", name: "无发热"}
			],
			
			rules: {
				commodityNum: {
					rules: [
						{
							required: true,
							errorMessage: '请填写用药数量'
						},
						{
							pattern: "^[1-9]\\d*$",
							errorMessage: '用药数量必须为数字'
						}
					]
				},
				frequency: {
					rules: [
						{
							required: true,
							errorMessage: '请填写用药频率'
						}
					]
				},
				onceDosage: {
					rules: [
						{
							required: true,
							errorMessage: '请填写单次用量'
						}
					]
				},
				useMethod: {
					rules: [
						{
							required: true,
							errorMessage: '请填写用药方法'
						}
					]
				},
				totalCharge: {
					rules: [
						{
							required: true,
							message: '请填写药量天数'
						},
						{
							pattern: "^[1-9]\\d*$",
							errorMessage: '用药数量必须为数字'
						}
					]
				},
			},
		};
	},
	onLoad(option) {
		this.clearRecipeForm();
		this.id = option.id;
		
		// 处方类型
		this.recipeForm.recipeType = option.recipeType == 1 ? 1 : 0; //0西药 1中药
		this.category = option.recipeType == 1 ? "7" : '4,5,6';
		
		// 处理诊断数据
		if (option.diseasesName && option.diseasesCode) {
			this.renderSickness(option.diseasesName, option.diseasesCode)
		}
		
		// 设置数据
		this.setRecipeForm(this.recipeForm);
		
		if (this.id) {
			this.drRecipeDetail();
		}
		this.queryDictItemsByCode("frequency", "frequencyList")
		this.queryDictItemsByCode("useMethod", "useMethodList")
		this.getPharmacyList()
	},
	onShow() {
		this.checkDisabledBtn();
	},
	methods: {
		...mapMutations({
			setRecipeForm: 'setRecipeForm',
			clearRecipeForm: 'clearRecipeForm',
			setRecipeDetailDTO: 'setRecipeDetailDTO'
		}),
		
		// 字典查询
		queryDictItemsByCode(code, list) {
			this.$api.queryDictItemsByCode({
				params: {
					code: code
				}
			}).then(res => {
				res.forEach(key => {
					this[list].push(key.text);
				});
			});
		},
		
		// 展开疾病列表
		showSearchPanel() {
			this.searchPanelVisible = true
		},
		// 收起疾病列表
		hideSearchPanel() {
			this.sicknessKeyword = ''
			this.searchPanelVisible = false
		},
		// 删除诊断
		delSickness(sickness, index) {
			this.sicknessSelectedTemp.splice(index, 1)
			this.setSickness()
		},
		// 选择诊断
		sicknessClick(sickness) {
			if (!this.sicknessSelectedTemp.includes(sickness)) {
				this.sicknessSelectedTemp.push(sickness)
			}
			this.setSickness()
		},
		// 设置诊断数据
		setSickness() {
			const sicknessName = this.sicknessSelectedTemp.map((item) => {
				return item.sicknessName
			})
			const sicknessCode = this.sicknessSelectedTemp.map((item) => {
				return item.code
			})
			this.recipeForm.diagnose = sicknessName.join('|') // 以前的【诊断】字段
			this.recipeForm.sicknessName = sicknessName.join('|')
			this.recipeForm.sicknessCode = sicknessCode.join('|')
			this.checkDisabledBtn()
		},
		// 疾病列表
		getSicknessList() {
			onlyResolvesLast(this.querySicknessList())
		},
		async querySicknessList(e) {
			const { code, result } = await this.$api.querySicknessPage({
				params:{
					pageNo:1,
					pageSize:10,
					sicknessName: this.sicknessKeyword,
					type: this.prescType,
				}
			})
			if (code === 200) {
				this.sicknessList = result.records
			} else {
				uni.showToast({
					title: '查询疾病列表失败',
					icon: 'none'
				});
			}
		},
		
		// 选择症状
		sympotmNameChange(e) {
			if (!this.sympotmSelectedTemp.includes(this.sympotmList[e.detail.value])) {
				this.sympotmSelectedTemp.push(this.sympotmList[e.detail.value])
			}
			this.setSympotm()
		},
		// 删除症状
		delSympotm(sympotm, index) {
			this.sympotmSelectedTemp.splice(index, 1)
			this.setSympotm()
		},
		// 设置症状
		setSympotm() {
			const str = this.sympotmSelectedTemp.map((item) => {
				return item.name
			})
			const codeStr = this.sympotmSelectedTemp.map((item) => {
				return item.value
			})
			this.recipeForm.sympotmName = str.join('|')
			this.recipeForm.sympotmCode = codeStr.join('|')
			this.checkDisabledBtn()
		},

		// 获取药房列表
		getPharmacyList() {
			this.$api.getPharmacyList().then(e => {
				const { code, result } = e
				if (code == 200) {
					this.pharmacyList = result
				} else {
					uni.showToast({
						title: res.message,
						icon: 'none'
					});
				}
			})
		},
		// 药房更换
		pharmacyChange(e) {
			this.pharmacy_id_raw = false
			this.pharmacy_index = Number(e.detail.value)
			this.setRecipeDetailDTO([])  //清空药品信息
		},
		// 设置药品
		check_druglist() {
			if (this.pharmacy_id_raw) {
				this.gotoRouter('/pages-doctor/drugList/drugList?tabShow=1&category=' + this.category + '&merchantId=' + this.pharmacy_obj.id)
			} else {
				if (this.pharmacyList.index != -1) {
					this.gotoRouter('/pages-doctor/drugList/drugList?tabShow=1&category=' + this.category + '&merchantId=' + this.pharmacyList[this.pharmacy_index].id)
				} else {
					uni.showToast({
						title: '请选择药房',
						icon: 'none'
					});
				}
			}
		},
		// 删除已设置的药品
		deleteDosage(index) {
			this.recipeForm.recipeDetailDTO.splice(index, 1);
			this.setRecipeForm(this.recipeForm);
		},
		
		// 中药处方-选择用药频率
		frequencyChange(e) {
			this.recipeForm.drugUseVo.frequency = this.frequencyList[e.detail.value]
			this.checkDisabledBtn()
		},
		// 中药处方-选择用药方法
		useMethodChange(e) {
			this.recipeForm.drugUseVo.useMethod = this.useMethodList[e.detail.value]
			this.checkDisabledBtn()
		},
		
		// 校验按钮
		checkDisabledBtn() {
			let b = false;
			Object.keys(this.recipeForm).forEach(key => {
				if (this.recipeForm[key] === '' || this.recipeForm[key] === null || (typeof this.recipeForm[key] == 'object' && this.recipeForm[key].length == 0)) {
					if (key != 'opinion') {
						b = true;
					}
				}
			});
		
			if (this.recipeForm.recipeType == 1) {
				Object.keys(this.recipeForm.drugUseVo).forEach(key => {
					if (this.recipeForm.drugUseVo[key] === '' || this.recipeForm.drugUseVo[key] === null) {
						if (key != 'opinion') {
							b = true;
						}
					}
				});
			}
			this.disabled = b;
			this.setRecipeForm(this.recipeForm);
		},
		// 校验表单
		formSubmit(type) {
			if (this.category == 5) {
				this.$refs.form
					.submit()
					.then(res => {
						if (type == 0) {
							this.addDrRecipe();
						} else {
							this.editDrRecipe();
						}
					})
					.catch(err => {
						console.log('表单错误信息：', err);
					});
			} else {
				if (type == 0) {
					this.addDrRecipe();
				} else {
					this.editDrRecipe();
				}
			}
		},
		
		// 常用处方详情
		drRecipeDetail() {
			let that = this
			this.$api.drRecipeDetail({
					params: {
						id: this.id
					}
				})
				.then(res => {
					if (res.code == 200) {
						// 回显疾病
						if (res.result.sicknessName && res.result.sicknessCode) {
							that.renderSickness(res.result.sicknessName, res.result.sicknessCode)
						}
						
						// 回显症状
						if (res.result.sympotmName && res.result.sympotmCode) {
							that.renderSympotm(res.result.sympotmName, res.result.sympotmCode)
						}
						
						if (res.result.recipeDetailDTO && res.result.recipeDetailDTO.length) {
							// 回显药品
							res.result.recipeDetailDTO.forEach((key, index) => {
								key.commodity.buyNum = key.commodityNum
								res.result.recipeDetailDTO[index] = {
									...key.commodity,
									...key
								}
							});
							
							// 回显药房
							this.pharmacy_id_raw = true
							this.pharmacy_obj.name = res.result.recipeDetailDTO[0].commodity.merchantName
							this.pharmacy_obj.id = res.result.recipeDetailDTO[0].commodity.merchantId
						} else {
							this.pharmacy_id_raw = false
						}
						
						this.setRecipeForm(res.result);
					} else {
						uni.showToast({
							title: res.message,
							icon: 'none'
						});
					}
				});
		},
		// 添加常用处方
		addDrRecipe() {
			this.$api.addDrRecipe({
				data: this.recipeForm
			}).then(res => {
				if (res.code == 200) {
					uni.showToast({
						title: '保存成功',
						icon: 'none'
					});
					this.clearRecipeForm();
					uni.navigateBack({
						delta: 1
					});
				} else {
					uni.showToast({
						title: res.message,
						icon: 'none'
					});
				}
			});
		},
		// 修改常用处方信息
		editDrRecipe() {
			this.$api.editDrRecipe({
				data: this.recipeForm
			}).then(res => {
				if (res.code == 200) {
					uni.showToast({
						title: '保存成功',
						icon: 'none'
					});
	
					this.clearRecipeForm();
					uni.navigateBack({
						delta: 1
					});
				} else {
					uni.showToast({
						title: res.message,
						icon: 'none'
					});
				}
			});
		},
		// 删除常用处方
		removeDrRecipe() {
			uni.showModal({
				title: '确认要删除该常用处方吗？',
				success: res => {
					if (res.confirm) {
						this.$api.removeDrRecipe({
							params: {
								id: this.id
							}
						}).then(res => {
							if (res.code == 200) {
								uni.showToast({
									title: '删除成功',
									icon: 'none'
								});
								uni.navigateBack({
									delta: 1
								});
							} else {
								uni.showToast({
									title: res.message,
									icon: 'none'
								});
							}
						});
					}
				}
			});
		},
		
		// 回显疾病诊断
		renderSickness (diseasesName, diseasesCode) {
			let arr = []
			let arr1 = diseasesName.split('|')
			let arr2 = diseasesCode.split('|')
			arr1.forEach((item, index)=>{
				arr.push({
					sicknessName: item,
					code: arr2[index]
				})
			}) 
			this.sicknessSelectedTemp = arr
			this.recipeForm.diagnose = diseasesName
			this.recipeForm.sicknessName = diseasesName
			this.recipeForm.sicknessCode = diseasesCode
		},
		// 回显症状
		renderSympotm (sympotmName, sympotmCode) {
			let arr = []
			let arr1 = sympotmName.split('|')
			let arr2 = sympotmCode.split('|')
			arr1.forEach((item, index)=>{
				arr.push({
					name: item,
					value: arr2[index]
				})
			}) 
			this.sympotmSelectedTemp = arr
			this.recipeForm.sympotmName = sympotmName
			this.recipeForm.sympotmCode = sympotmCode
		},
	}
};
</script>

<style lang="less">
@import './editPresc.less';
</style>
